import socket
import threading
import socketserver
import json, types,string
import os, time
import logging
import subprocess

import buildDock
import db
import login


class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
    """
    """
    def handle(self):
        logger = logging.getLogger("TCPServer")
        data = self.request.recv(1024).decode()
        jdata = json.loads(data)
        logger.info("Receive data from '%r'"% (data))
        execName = jdata['name']
        execName = 'app/' + execName
        subprocess.Popen(['python3', execName])

        cur_thread = threading.current_thread()
        response = {'result': 'ok'}
        jresp = json.dumps(response)
        self.request.sendall(jresp.encode())
           
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    pass

if __name__ == "__main__":
    print('started')
    HOST, PORT = "0.0.0.0", 22224
    
    logger = logging.getLogger("TCPServer")
    logger.setLevel(logging.INFO)

    fh = logging.FileHandler("1.log")

    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -\
%(message)s')
    fh.setFormatter(formatter)

    logger.addHandler(fh)

    logger.info("Program started")
    socketserver.TCPServer.allow_reuse_address = True
    server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
    ip, port = server.server_address

    server_thread = threading.Thread(target=server.serve_forever)
    server_thread.daemon = True
    server_thread.start()
    logger.info("Server loop running in thread:" + server_thread.name)
    logger.info(" .... waiting for connection")

    server.serve_forever()
